<template>
  <div class="register-container">
    <!-- 全局提示悬浮窗 -->
    <div 
      class="toast" 
      :class="{ 'toast-show': showToast, 'toast-error': toastType === 'error', 'toast-success': toastType === 'success' }"
      @click="hideToast"
    >
      <div class="toast-content">
        <i :class="toastIcon"></i>
        <span>{{ toastMessage }}</span>
      </div>
      <div class="toast-progress" :style="{ width: progressWidth }"></div>
    </div>

    <!-- 商户资质上传弹窗 -->
    <el-dialog
      v-model="showMerchantDialog"
      title="商户资质上传"
      width="500px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="merchant-upload">
        <!-- 店铺名输入框 -->
        <div class="form-group">
          <label>店铺名称：</label>
          <el-input
            v-model="shopName"
            placeholder="请输入店铺名称"
            clearable
          />
        </div>

        <!-- 营业执照上传 -->
        <div class="upload-item">
          <label>营业执照：</label>
          <el-upload
            :action="uploadUrl"
            :on-success="handleLicenseSuccess"
            :show-file-list="false"
            accept="image/*"
            class="avatar-uploader"
          >
            <el-avatar :src="licenseUrl || defaultAvatar" :size="120" class="avatar" />
            <template #tip>
              <div class="el-upload__tip">点击上传营业执照（JPG/PNG，最大5MB）</div>
            </template>
          </el-upload>
        </div>
      </div>

      <template #footer>
        <el-button @click="cancelMerchantRegister">取消注册</el-button>
        <el-button 
          type="primary" 
          @click="confirmMerchantRegister" 
          :disabled="!canSubmit"
          :loading="isSubmitting"
        >
          确认提交
        </el-button>
      </template>
    </el-dialog>

    <!-- 注册表单区域 -->
    <div class="register-box">
      <div class="register-header">
        <h2>购物商城注册</h2>
        <p>填写信息，开启购物之旅</p>
      </div>
      
      <div class="form-group">
        <label>用户名：</label>
        <input 
          type="text" 
          placeholder="请设置用户名" 
          class="input-field" 
          v-model.trim="username"
        >
      </div>
      
      <div class="form-group">
        <label>手机号：</label>
        <input 
          type="tel" 
          placeholder="请输入手机号码" 
          class="input-field" 
          v-model.trim="phone"
        >
      </div>
      
      <div class="form-group">
        <label>邮箱：</label>
        <input 
          type="email" 
          placeholder="请输入常用邮箱" 
          class="input-field" 
          v-model.trim="email"
        >
      </div>
      
      <div class="form-group code-group">
        <label>验证码：</label>
        <input 
          type="text" 
          placeholder="请输入邮箱验证码" 
          class="input-field" 
          v-model.trim="emailCode"
        >
        <button 
          class="code-btn" 
          :disabled="isCountdown" 
          @click="handleSendCode"
        >
          {{ countdownText }}
        </button>
      </div>
      
      <div class="form-group">
        <label>密码：</label>
        <input 
          type="password" 
          placeholder="请设置密码（6-20位）" 
          class="input-field" 
          v-model.trim="password"
        >
      </div>
      
      <div class="form-group identity-group">
        <label>身份：</label>
        <el-radio-group v-model="identity">
          <el-radio label="buyer">买家</el-radio>
          <el-radio label="merchant">商户</el-radio>
        </el-radio-group>
      </div>
      
      <button class="register-btn" @click="handleRegister">完成注册</button>
      
      <div class="link-group">
        <router-link to="/login">已有账号？去登录</router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElRadioGroup, ElRadio, ElDialog, ElUpload, ElButton, ElInput, ElAvatar } from 'element-plus';
import { Plus, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus'
import defaultAvatar from '@/assets/default.png'

const router = useRouter();

// 表单数据
const username = ref('');
const password = ref('');
const phone = ref('');
const email = ref('');
const emailCode = ref('');
const identity = ref('buyer');
const shopName = ref('');
const countdown = ref(0);
const isCountdown = computed(() => countdown.value > 0);
const isSubmitting = ref(false);

// 商户资质上传相关状态
const showMerchantDialog = ref(false);
const licenseUrl = ref('');
const baseUrl = 'http://localhost:8080'
const uploadUrl = '/api/upload/avatar'

// 计算是否满足提交条件
const canSubmit = computed(() => {
  return shopName.value && licenseUrl.value;
});

// 全局提示状态管理
const showToast = ref(false);
const toastMessage = ref('');
const toastType = ref('info');
const toastIcon = ref('');
const progressWidth = ref('100%');
let toastTimer = null;
let progressTimer = null;

// 显示提示窗
const showToastMessage = (message, type = 'info', duration = 3000) => {
  if (toastTimer) clearTimeout(toastTimer);
  if (progressTimer) clearInterval(progressTimer);
  
  toastMessage.value = message;
  toastType.value = type;
  
  switch (type) {
    case 'success':
      toastIcon.value = '✅';
      break;
    case 'error':
      toastIcon.value = '❌';
      break;
    default:
      toastIcon.value = '💡';
  }
  
  showToast.value = true;
  progressWidth.value = '100%';
  
  toastTimer = setTimeout(() => {
    hideToast();
  }, duration);
  
  const startTime = Date.now();
  progressTimer = setInterval(() => {
    const elapsed = Date.now() - startTime;
    const percentage = Math.max(0, 100 - (elapsed / duration * 100));
    progressWidth.value = `${percentage}%`;
    
    if (percentage <= 0) {
      clearInterval(progressTimer);
    }
  }, 30);
};

// 隐藏提示窗
const hideToast = () => {
  showToast.value = false;
  if (toastTimer) clearTimeout(toastTimer);
  if (progressTimer) clearInterval(progressTimer);
};

// 上传成功处理
const handleLicenseSuccess = (response) => {
  if (response.url) {
    licenseUrl.value = response.url.startsWith('http') ? response.url : `${baseUrl}${response.url}`
    ElMessage.success('营业执照上传成功')
  } else {
    ElMessage.error('营业执照上传失败: ' + (response.message || '未知错误'))
  }
};

// 取消商户注册
const cancelMerchantRegister = () => {
  showMerchantDialog.value = false;
  resetForm();
};

// 确认商户注册
const confirmMerchantRegister = async () => {
  isSubmitting.value = true;
  
  try {
    // 1. 先完成用户注册
    const userResponse = await axios.post('/api/user-account/register', {
      username: username.value,
      password: password.value,
      phone: phone.value,
      emailCode: emailCode.value,
      email: email.value,
      identity: identity.value
    });

    if (userResponse.data.code !== '200') {
      throw new Error(userResponse.data.message || '用户注册失败');
    }

    console.log(userResponse)
    // 2. 保存商户信息到 merchant_info 表
    const merchantResponse = await axios.post('/api/merchant-info/save', {
      userId: userResponse.data.data.id,
      shopName: shopName.value,
      businessLicense: licenseUrl.value,
      auditStatus: 0 // 初始状态为待审核
    });

    if (merchantResponse.data.code === '200') {
      showToastMessage('商户注册成功，请等待审核', 'success');
      setTimeout(() => {
        router.push('/login');
      }, 1500);
    } else {
      throw new Error(merchantResponse.data.message || '商户信息保存失败');
    }
  } catch (error) {
    console.error('注册过程中出错:', error);
    showToastMessage(error.message || '注册失败，请稍后重试', 'error');
  } finally {
    isSubmitting.value = false;
  }
};

// 邮箱格式验证
const validateEmail = (email) => {
  const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  return re.test(String(email).toLowerCase());
};

// 手机号格式验证
const validatePhone = (phone) => {
  const re = /^1[3-9]\d{9}$/;
  return re.test(String(phone));
};

// 发送验证码
const handleSendCode = () => {
  if (!email.value) {
    showToastMessage('请输入邮箱', 'error');
    return;
  }
  
  if (!validateEmail(email.value)) {
    showToastMessage('请输入正确的邮箱格式', 'error');
    return;
  }
  
  axios.get(`/api/captcha/sendCaptcha?email=${email.value}`)
    .then((response) => {
      if (response.data === '验证码已发送') {
        showToastMessage('验证码已发送到邮箱', 'success');
        startCountdown(60);
      } else {
        showToastMessage('验证码发送失败，请重试', 'error');
      }
    })
    .catch((error) => {
      console.error('发送验证码错误：', error);
      showToastMessage('网络错误，请稍后重试', 'error');
    });
};

// 倒计时逻辑
const startCountdown = (seconds) => {
  countdown.value = seconds;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 倒计时文本
const countdownText = computed(() => {
  return countdown.value > 0 ? `${countdown.value}秒后重发` : '获取验证码';
});

// 注册逻辑
const handleRegister = () => {
  // 表单验证
  if (!username.value) {
    showToastMessage('请输入用户名', 'error');
    return;
  }
  
  if (!phone.value || !validatePhone(phone.value)) {
    showToastMessage('请输入正确的手机号', 'error');
    return;
  }
  
  if (!email.value || !validateEmail(email.value)) {
    showToastMessage('请输入正确的邮箱', 'error');
    return;
  }
  
  if (!emailCode.value) {
    showToastMessage('请输入验证码', 'error');
    return;
  }
  
  if (!password.value || password.value.length < 6) {
    showToastMessage('请设置6位以上的密码', 'error');
    return;
  }
  
  // 如果是商户注册，弹出资质上传窗口
  if (identity.value === 'merchant') {
    showMerchantDialog.value = true;
  } else {
    // 普通用户注册逻辑
    const requestData = {
      username: username.value,
      password: password.value,
      phone: phone.value,
      emailCode: emailCode.value,
      email: email.value,
      identity: identity.value
    };
    
    axios.post('/api/user-account/register', requestData)
      .then((response) => {
        if (response.data.code === '200') {
          showToastMessage('注册成功，正在跳转登录页...', 'success');
          setTimeout(() => {
            router.push('/login');
          }, 1500);
        } else {
          showToastMessage(response.data.message || '注册失败', 'error');
        }
      })
      .catch((error) => {
        console.error('注册请求错误：', error);
        showToastMessage('网络错误，请稍后重试', 'error');
      });
  }
};

// 重置表单
const resetForm = () => {
  username.value = '';
  password.value = '';
  phone.value = '';
  email.value = '';
  emailCode.value = '';
  identity.value = 'buyer';
  shopName.value = '';
  licenseUrl.value = '';
};
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  /* background: url('@/assets/bg-shop.jpg') no-repeat center center; */
  background-size: cover;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
}

.register-box {
  width: 450px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.register-header {
  text-align: center;
  margin-bottom: 25px;
}

.register-header h2 {
  font-size: 24px;
  color: #409eff;
  margin-bottom: 8px;
}

.register-header p {
  color: #666;
  font-size: 14px;
}

.form-group {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.form-group label {
  width: 80px;
  font-size: 14px;
  color: #333;
}

.input-field {
  flex: 1;
  height: 40px;
  padding: 0 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  outline: none;
  font-size: 14px;
}

.input-field:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(230, 0, 18, 0.1);
}

.code-group {
  display: flex;
  align-items: center;
}

.code-btn {
  margin-left: 10px;
  width: 120px;
  height: 40px;
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.code-btn:disabled {
  background: #eee;
  color: #999;
  cursor: not-allowed;
}

.identity-group {
  padding-left: 80px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.register-btn {
  width: 100%;
  height: 44px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  margin-top: 10px;
}

.register-btn:hover {
  background: #2f96fc;
}

.link-group {
  text-align: center;
  margin-top: 20px;
}

.link-group a {
  color: #409eff;
  text-decoration: none;
  font-size: 14px;
}

.link-group a:hover {
  text-decoration: underline;
}

/* 全局提示悬浮窗样式 */
.toast {
  position: fixed;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);
  padding: 12px 20px;
  border-radius: 6px;
  color: white;
  font-size: 14px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 2000;
  display: flex;
  flex-direction: column;
  min-width: 280px;
  max-width: 400px;
  transition: all 0.3s ease;
  opacity: 0;
}

.toast-show {
  top: 20px;
  opacity: 1;
}

.toast-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.toast-error {
  background-color: #ff4d4f;
}

.toast-success {
  background-color: #52c41a;
}

.toast-info {
  background-color: #1890ff;
}

.toast-progress {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 3px;
  background-color: rgba(255, 255, 255, 0.5);
  transition: width 0.3s linear;
}

/* 商户上传弹窗样式 */
.merchant-upload {
  padding: 0 20px;
}

.upload-item {
  margin-bottom: 20px;
}

.upload-item label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  margin-top: 7px;
}

/* 上传组件样式 */
.avatar-uploader {
  text-align: center;
  .el-avatar {
    border: 2px solid #e4e7ed;
    border-radius: 8px;
    transition: transform 0.3s, border-color 0.3s;
    &:hover {
      transform: scale(1.05);
      border-color: #409eff;
    }
  }
  .el-upload__tip {
    margin-top: 12px;
    color: #606266;
    font-size: 14px;
  }
}
</style>